
import sys
import os.path 

cur_path = os.path.dirname(__file__)
parent_path = os.path.abspath(os.path.join(cur_path, '..'))
sys.path.append(parent_path)

import redis
import pymongo

import time
import re
import urllib


a='115.206.45.149 12852441155,12849526049,12852441173,13545708779,13545740080,13071815319,12849518391 /say/v1/iframe.html?seller_nick=%E6%B7%98%E9%87%91%E7%94%B5%E5%95%86'


def parse_line(log_line):
    try:
        loginfo = log_line.split('\t')[1].split(' ')
        iidlist = loginfo[1].split(',')
        for i in  loginfo[2].split('?')[1].split('&'):
            if 'seller_nick' in i:
                seller_nick = i
                break
        seller_nick = urllib.unquote(seller_nick.split('=')[1])
    except:
        return None
    return (seller_nick.strip(), iidlist)

def view_stat_internal(fn, rdb):
    for line in fn:
        r = parse_line(line)
        if not r:
            continue
        seller_nick, numiid = r
        niid = len(numiid)
        rdb.incr(seller_nick, niid)

def view_stat(fn, rdb, mdb):
    view_stat_internal(fn, rdb)
    daystr = time.strftime('%Y%m%d', time.localtime((time.time()-86400)))
    for i in rdb.keys():
        views = int(rdb.get(i))
        keystr = ':'.join([i, daystr])
        mdb.dailyview.save({'_id':keystr, 'view':views})
        ts = mdb.totalstat.find_one({'_id':i})
        if not ts:
            mdb.totalstat.save({'_id':i, 
                'maxclick':0, 'maxclickday':daystr, 
                'maxview':views, 'maxviewday':daystr,
                'totalclick': 0, 'totalview':views})
        else:
            mdb.totalstat.update({'_id':i}, {'$inc':{'totalview':views}})
            if 'maxview' in ts and views > ts['maxview']:
                mdb.totalstat.update({'_id':i}, {'$set':{'maxview':views, 'maxviewday':daystr}})
            
        
def main(logfile):
    rdb = redis.StrictRedis(host='127.0.0.1', port=56379, db=6)
    rdb.flushdb()
    mdb = pymongo.Connection('127.0.0.1:57324').saystat
    fn = open(logfile)
    view_stat(fn, rdb, mdb)


if __name__ == '__main__':
    main(sys.argv[1])
